﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SAPbouiCOM;
using SAPbobsCOM;

namespace BoAddonBiz_FreightForwarder.Land
{
    [BoAddonBiz_FreightForwarder.BusinessBase.ControlB1Form(IsNew = true, FormType = B1FormTypes.ado_AVA_LN_CustomsClearance)]
    public class B1Form_CustomsClearance_Land : B1Form_BaseOperationSon
    {
        #region public properties
        public override string FatherField
        {
            get { return "U_IsClearance"; }
        }

        public override string FatherUDS
        {
            get { return "OCTC_UID"; }
        }

        public override string ThisTableName
        {
            get { return "@AVA_LN_OCTC"; }
        }

        public override string ThisSubTableName
        {
            get { return "@AVA_LN_CTC1"; }
        }

        public override string ThisSubTableName2
        {
            get { return null; }
        }

        public override string ThisObjectCode
        {
            get { return "AVA_LN_Clearance"; }
        }
        #endregion

        private string FormUID_OBNO = string.Empty;

        #region constructor
        public B1Form_CustomsClearance_Land()
            : base()
        {
            this.frm_ChooseFormListEvent += new SAPBoAddon.IB1FormEvents.B1ChooseFormListEventEventHandler(B1Form_CustomsClearance_frm_ChooseFormListEvent);
            this.frm_ItemEvent += new SAPBoAddon.IB1FormEvents.B1ItemEventEventHandler(B1Form_CustomsClearance_frm_ItemEvent);
        }

        void B1Form_CustomsClearance_frm_ItemEvent(SAPBoAddon.B1AddonBase.B1ItemEvent pVal, ref bool BubbleEvent)
        {
            /*计算行总计*/
            if (pVal.ItemUID == "mtx_0" && (pVal.ColUID == "col_14" || pVal.ColUID == "col_15") && pVal.ItemChanged && pVal.Row > 0)
            {
                Utils.CalcLineTotal(this.CurrentForm, "mtx_0", "@AVA_LN_CTC1", pVal.Row);
            }
            if (pVal.ItemUID == "65" && pVal.ItemChanged)
            {
                SAPbouiCOM.Form OBNOForm = SBOApp.Forms.Item(FormUID_OBNO);
                SAPBoAddon.B1Assistant.Item.SetValue(OBNOForm, "cargo_60", SAPBoAddon.B1Assistant.Item.GetValue(this.CurrentForm, pVal.ItemUID));
            }
            if (pVal.ItemUID == "109" && pVal.ItemChanged)
            {
                SAPbouiCOM.Form Form_OBNO = SBOApp.Forms.Item(FormUID_OBNO);
                Form_OBNO.DataSources.UserDataSources.Item("PackType").ValueEx = SAPBoAddon.B1Assistant.Item.GetValue(this.CurrentForm, pVal.ItemUID).ToString();
                Utils.SetPackType(FormType_PackType.OARP_UID, Form_OBNO);
                Utils.SetPackType(FormType_PackType.OATC_UID, Form_OBNO);
            }
        }
        #endregion

        #region methods
        void B1Form_CustomsClearance_frm_ChooseFormListEvent(SAPBoAddon.B1AddonBase.B1ChooseFormList pVal, ref bool BubbleEvent)
        {
            if (pVal.Before_Action)
            {
                SAPbouiCOM.ChooseFromList cfl = this.CurrentForm.ChooseFromLists.Item(pVal.ChooseFromListUID);
                SAPbouiCOM.Conditions cons;
                SAPbouiCOM.Condition con;
                switch (pVal.ChooseFromListUID)
                {
                    case "CFL_OCRD":
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "CardType";
                        con.CondVal = "S";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    case "CFL_OCRD_D":
                    case "CFL_OCRD_C":
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "QryGroup11";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_OR;
                        con = cons.Add();
                        con.Alias = "QryGroup12";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    case "CFL_OCRD_CB":
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "CardType";
                        con.CondVal = "S";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                }
            }
            else
            {
                if (pVal.Action_Success)
                {
                    SAPbouiCOM.Matrix omtx = default(SAPbouiCOM.Matrix);
                    SAPbouiCOM.DBDataSource dbds = this.CurrentForm.DataSources.DBDataSources.Item(ThisTableName);
                    if (pVal.ChooseFromListUID == "CFL_OCRD")//客户
                    {
                        dbds.SetValue("U_CardCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_CardName", dbds.Offset, pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                        dynamic Cntct = Utils.GetDefaultContractPerson(this.SBOCompany, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        if (Cntct != null)
                        {
                            dbds.SetValue("U_CntctCode", dbds.Offset, Cntct.FullName);
                        }
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCRD_CB")//报关行
                    {
                        dbds.SetValue("U_CustomsBrokerCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_CustomsBrokerName", dbds.Offset, string.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardName", 0).ToString()) ? pVal.SelectedObjects.GetValue("CardFName", 0).ToString() : pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                        dynamic Cntct = Utils.GetDefaultContractPerson(this.SBOCompany, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        if (Cntct != null)
                        {
                            dbds.SetValue("U_CBCntctCode", dbds.Offset, Cntct.FullName);
                            dbds.SetValue("U_CBCntctTel", dbds.Offset, Cntct.Cellolar);
                            dbds.SetValue("U_CBCntctEmail", dbds.Offset, Cntct.Email);
                        }
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCRD_D")//收发货单位
                    {
                        dbds.SetValue("U_DeliverCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_DeliverName", dbds.Offset, string.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardName", 0).ToString()) ? pVal.SelectedObjects.GetValue("CardFName", 0).ToString() : pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCRD_C")//经营单位
                    {
                        dbds.SetValue("U_CompanyCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_CompanyName", dbds.Offset, string.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardName", 0).ToString()) ? pVal.SelectedObjects.GetValue("CardFName", 0).ToString() : pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                        dbds.SetValue("U_CusComInsRegCode", dbds.Offset, pVal.SelectedObjects.GetValue("U_CusComInsRegCode", 0).ToString());
                        //dbds.SetValue("U_CusRegCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                        dbds.SetValue("U_CusRegCode", dbds.Offset, pVal.SelectedObjects.GetValue("U_CusRegCode", 0).ToString());/*取客户[海关注册编码] 2012-7-16 by WangPeng*/
                    }
                    else if (pVal.ChooseFromListUID == "CFL_PORT")
                    {
                        //之前的全部注释掉，ChooseFormList取值 出口口岸列表 modified by WangPeng 2012-7-6
                        dbds.SetValue("U_PortCode", dbds.Offset, pVal.SelectedObjects.GetValue("Code", 0).ToString());
                        dbds.SetValue("U_Port", dbds.Offset, pVal.SelectedObjects.GetValue("Name", 0).ToString());

                        //dbds.SetValue("U_PortCode", dbds.Offset, pVal.SelectedObjects.GetValue("U_PortCode", 0).ToString());
                        //dbds.SetValue("U_Port", dbds.Offset, pVal.SelectedObjects.GetValue("U_PortNameE", 0).ToString());
                        //dbds.SetValue("U_LoadingPortCode", dbds.Offset, pVal.SelectedObjects.GetValue("U_CityCode", 0).ToString());
                        //dbds.SetValue("U_LoadingPort", dbds.Offset, pVal.SelectedObjects.GetValue("U_CityNameE", 0).ToString());
                        //dbds.SetValue("U_TransportCountry", dbds.Offset, pVal.SelectedObjects.GetValue("U_CountryNameE", 0).ToString());
                    }
                    //行 商品编码
                    else if (pVal.ChooseFromListUID == "CFL_PdtCode")
                    {
                        dbds = this.CurrentForm.DataSources.DBDataSources.Item(ThisSubTableName);
                        omtx = (SAPbouiCOM.Matrix)this.CurrentForm.Items.Item("mtx_0").Specific;
                        dbds.Offset = this.GetDBDSOffSet(omtx, dbds, pVal.Row);
                        omtx.GetLineData(pVal.Row);
                        dbds.SetValue("U_HSCode", dbds.Offset, pVal.SelectedObjects.GetValue("U_HSCode", 0).ToString());
                        //dbds.SetValue("U_ProductName", dbds.Offset, pVal.SelectedObjects.GetValue("U_DescriptionC", 0).ToString());
                        omtx.SetLineData(pVal.Row);
                    }
                }
            }
        }
        #endregion

        #region override/private methods
        protected override void FormInfoSetting(SAPBoAddon.B1FormSetting FormSetting)
        {
            FormSetting.FormType = B1FormTypes.ado_AVA_LN_CustomsClearance;
            FormSetting.FormFileName = "AVA_LN_CustomsClearanceForm.srf";

            FormSetting.AutoGetObjectNextNumber = true;
            FormSetting.MatrixSetting.MtxUID = "mtx_0";
            FormSetting.MatrixSetting.AutoAddNewLine = true;
            FormSetting.MatrixSetting.MenuAddNewLine = false;//居然要设置这个属性才可以自动添加行？
            FormSetting.MatrixSetting.NotAllowNoLineSave = false;
            FormSetting.MatrixSetting.AutoLineKeyCol = "col_12";//货物编号
            FormSetting.MatrixSetting.AddLineAfterButtonPressed = true;
            FormSetting.MatrixSetting.BeforeSaveDeleteNoValueLine = true;
            FormSetting.MatrixSetting.BeforeSaveFixDbDataSourceData = false;
            FormSetting.MatrixSetting.TableKeyField = "LineId";
            FormSetting.MatrixSetting.TableVisOrder = "VisOrder";
            FormSetting.MatrixSetting.PrimaryLineCol = "col_f";
            FormSetting.MatrixSetting.TableName = "@AVA_LN_CTC1";
            FormSetting.MatrixSetting.Add();

            base.FormInfoSetting(FormSetting);
        }

        protected override void InitializeForm(SAPBoAddon.B1FormInitializePar InitPar)
        {
            Utils.InitialItemComboBox(this.SBOCompany, this.CurrentForm.Items.Item("57"), "DocCurrCod", "CurrName", "OCRN", "DocCurrCod", null, null, true);//币种
            Utils.InitialItemComboBox(this.SBOCompany, this.CurrentForm.Items.Item("75"), "Code", "Name", "@AVA_FF_OTRM", "Code", null, null, true);//贸易方式
            Utils.InitialItemComboBox(this.SBOCompany, this.CurrentForm.Items.Item("77"), "Code", "Name", "@AVA_FF_BAMD", "Code", null, null, true);//成交方式
            Utils.InitialItemComboBox(this.SBOCompany, this.CurrentForm.Items.Item("69"), "Code", "Name", "@AVA_FF_PAMD", "Code", null, null, true);//交税方式
            //Utils.InitialItemComboBox(this.SBOCompany, this.CurrentForm.Items.Item("877"), "Code", "Name", "@AVA_FF_OSUC", "Code", null, null, true);//监管方式
            Utils.InitialItemComboBox(this.SBOCompany, this.CurrentForm.Items.Item("879"), "Code", "Name", "@AVA_FF_QTRT", "Code", null, null, true);//检疫要求
            //Utils.InitialItemComboBox(this.SBOCompany, this.CurrentForm.Items.Item("877_1"), "Code", "Name", "@AVA_FF_OSUC", "Code", null, null, true);//监管方式2
            Utils.InitialItemComboBox(this.SBOCompany, this.CurrentForm.Items.Item("885"), "Code", "Name", "@AVA_FF_OSTM", "Code", null, null, true);//结汇方式
            Utils.InitialMatrixComboBox(SBOCompany, this.CurrentForm.Items.Item("mtx_0").Specific, "col_20", "Code", "Name", "@AVA_FF_OSUC");//监管方式

            Utils.InitialMatrixComboBox(this.SBOCompany, this.CurrentForm.Items.Item("mtx_0").Specific, "col_16", "Code", "Name", "@AVA_FF_OPRI", null, null, null);//单位

            (this.CurrentForm.Items.Item("mtx_0").Specific as Matrix).AutoResizeColumns();//用SAPBoAddon.B1Assistant.Form.LoadToSBOApplciation()打开的窗体不会执行上述方法
            base.InitializeForm(InitPar);

            /*为matrix预添加一行*/
            Matrix_AutoAddLine();
            //得到滞报日期
            CalculationLagDeclarationDate(InitPar);

            if (!String.IsNullOrEmpty(InitPar.FatherFormUID))
            {
                Form listForm = SBOApp.Forms.Item(InitPar.FatherFormUID.Split(';')[0]);
                FormUID_OBNO = listForm.DataSources.UserDataSources.Item("ParentUID").Value;
                Form BNOForm = SBOApp.Forms.Item(listForm.DataSources.UserDataSources.Item("ParentUID").Value);
                DBDataSource dbds_obno = BNOForm.DataSources.DBDataSources.Item("@AVA_LN_OBNO");
                DBDataSource main = this.CurrentForm.DataSources.DBDataSources.Item(this.ThisTableName);
                if (this.CurrentForm.Mode == BoFormMode.fm_ADD_MODE)
                {

                    this.CurrentForm.DataSources.DBDataSources.Item("@AVA_LN_OCTC").SetValue("U_MainBill", 0, BNOForm.DataSources.DBDataSources.Item("@AVA_LN_OBNO").GetValue("U_MBLNumber", 0));
                    this.CurrentForm.DataSources.DBDataSources.Item("@AVA_LN_OCTC").SetValue("U_SplitBill", 0, BNOForm.DataSources.DBDataSources.Item("@AVA_LN_OBNO").GetValue("U_SBLNumber", 0));

                    Dictionary<string, string> mapping = new Dictionary<string, string>();
                    mapping.Add("U_TotalAmount", "U_CargoValue");
                    mapping.Add("U_TotalNumber", "U_Quantity");
                    mapping.Add("U_TotalWeight", "U_GrossWeight");
                    mapping.Add("U_TotalNetWeight", "U_BillingWeight");
                    List<string> filter = new List<string>();
                    filter.Add("U_BaseEntry");
                    filter.Add("U_BaseSerial");
                    filter.Add("U_Status");
                    filter.Add("U_ref1");
                    filter.Add("U_ref2");
                    filter.Add("U_Remarks");
                    Utils.CopyDBDS(dbds_obno, main, null, filter, mapping, true);

                    DBDataSource dbds_bno1 = BNOForm.DataSources.DBDataSources.Item("@AVA_LN_BNO1");
                    DBDataSource sub = this.CurrentForm.DataSources.DBDataSources.Item(this.ThisSubTableName);
                    Dictionary<string, string> mapping1 = new Dictionary<string, string>();
                    mapping1.Add("U_ProductName", "U_CargoName");
                    mapping1.Add("U_ProducEName", "U_CargoEName");
                    sub.Clear();
                    Utils.CopyDBDS(dbds_bno1, sub, null, null, mapping1, false);
                    main.SetValue("U_ContractNo", main.Offset, dbds_bno1.GetValue("U_ConNumber", dbds_bno1.Offset).Trim()); /*合同号*/
                    (this.CurrentForm.Items.Item("mtx_0").Specific as Matrix).LoadFromDataSource();
                }
                if (!string.IsNullOrEmpty(BNOForm.DataSources.UserDataSources.Item("PackType").ValueEx))
                {
                    main.SetValue("U_PackageDescription", main.Offset, BNOForm.DataSources.UserDataSources.Item("PackType").ValueEx);/*包装类型*/
                }
            }
        }

        /// <summary>
        /// 获取DBDS的Offset
        /// </summary>
        /// <param name="omtx"></param>
        /// <param name="dbds"></param>
        /// <param name="MtxcurrentRow"></param>
        /// <returns></returns>
        protected int GetDBDSOffSet(SAPbouiCOM.Matrix omtx, SAPbouiCOM.DBDataSource dbds, int MtxcurrentRow)
        {
            string keyVal = SAPBoAddon.B1Assistant.Matrix.GetCellValue(omtx, "col_LineId", MtxcurrentRow).ToString().Trim();
            string dbdsLineVal = string.Empty;
            for (int i = 0; i < dbds.Size; i++)
            {
                dbdsLineVal = dbds.GetValue("LineId", i).Trim();
                if (keyVal.Equals(dbdsLineVal))
                {
                    return i;
                }
            }
            return -1;
        }
        #endregion
        /// <summary>
        /// 得到滞报日期
        /// </summary>
        private void CalculationLagDeclarationDate(SAPBoAddon.B1FormInitializePar InitPar)
        {
            string FatherUid = SBOAddonBase.Forms.Item(InitPar.FatherFormUID.Split(';')[0]).UniqueID.ToString().Trim();
            FatherUid = SBOAddonBase.Forms.Item(FatherUid).DataSources.UserDataSources.Item("ParentUID").Value.ToString().Trim();
            SAPbouiCOM.DBDataSource dbds = SBOAddonBase.Forms.Item(FatherUid).DataSources.DBDataSources.Item("@AVA_LN_OBNO");
            string ATA = dbds.GetValue("U_ATA", dbds.Offset).Trim();
            if (!string.IsNullOrEmpty(ATA))
            {
                string ATAYear = ATA.Substring(0, 4);
                string ATAMoth = ATA.Substring(4, 2);
                string ATADay = ATA.Substring(6);
                DateTime dtimeATA = Convert.ToDateTime(ATAYear + "-" + ATAMoth + "-" + ATADay);
                DateTime LagDeclarationDate = dtimeATA.AddDays(14);
                SAPbouiCOM.EditText oEdit = this.CurrentForm.Items.Item("71").Specific;
                oEdit.Value = LagDeclarationDate.ToString("yyyyMMdd");
            }

        }
    }
}
